package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageRequestDto;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.WmChannelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {

    @Override
    public ResponseResult pageInfo(ChannelDto channelDto) {
//        查询频道名称
        Wrapper<WmChannel> query = new LambdaQueryWrapper<>();
//        判断频道名称是否为空
        if (!StringUtils.isEmpty(channelDto.getName())){
           ((LambdaQueryWrapper<WmChannel>) query).like(WmChannel::getName,channelDto.getName());
        }
//        进行分页
        IPage<WmChannel> page = new Page<>(channelDto.getPage(),channelDto.getSize());
        this.page(page,query);
//        返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(channelDto.getPage(), channelDto.getSize(), page.getTotal(), page.getRecords());
        return pageResponseResult;
    }

    @Override
    public ResponseResult<Integer> Insert(WmChannel channelDto) {
        System.out.println(channelDto);
//        判断参数和管道是否传递
        if (channelDto == null || StringUtils.isEmpty(channelDto.getName())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        判断数据库中是否有数据
        LambdaQueryWrapper<WmChannel> query = new LambdaQueryWrapper<>();
        query.eq(WmChannel::getName, channelDto.getName());
        int count = this.count(query);
        System.out.println(count);
        if (count > 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
//        如果不存在存入数据库
        channelDto.setCreatedTime(new Date());
        this.save(channelDto);
        return ResponseResult.okResult(channelDto.getId());
    }

    @Override
    public ResponseResult Channels() {

        LambdaQueryWrapper<WmChannel> query = new LambdaQueryWrapper<>();
//        查询
        query.orderByDesc(WmChannel::getId);
        List<WmChannel> list = this.list(query);
        return ResponseResult.okResult(list);
    }
}
